package com.ply.flashsalessystem.aopLog;

import com.google.gson.Gson;
import com.ply.flashsalessystem.entity.result.Result;
import com.ply.flashsalessystem.utils.AuthorityUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * @author XiaoPan
 * date: 2022/5/4 19:48
 * <p>
 * action:
 */
@Slf4j
@Aspect
@Component
public class AuthorityAop {
    @Autowired
    AuthorityUtils authorityUtils;
    /** 以 controller 包下定义的所有请求为切入点 */
    @Pointcut("@annotation( com.ply.flashsalessystem.annotation.AuthorityName)" +
            " || @annotation(com.ply.flashsalessystem.annotation.UserAuthority)" +
            " || @annotation(com.ply.flashsalessystem.annotation.StoreAuthority))")
    public void webLog() {}
    /**
     * 环绕
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        log.debug("开始权限验证");
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        String className = proceedingJoinPoint.getSignature().getDeclaringTypeName();
        String function = proceedingJoinPoint.getSignature().getName();

        if (!authorityUtils.pdAdminAuthority(className, function)){
            return Result.error().code(31000).message("没有权限操作");
        }
        return proceedingJoinPoint.proceed();
    }
}
